package com.cyz.web.app.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxyClient {


    public static void main(String[] args) {
        String username = "zhangsan";

        Ticketer buyer = new Ticketer(username);

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(buyer.getClass());

        enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> {
            Object obj;
            if (method.getName().equals("buyTicket")) {
                System.out.println("开始抢票定时任务");
                obj = methodProxy.invoke(buyer, objects);
                System.out.println("抢票成功，短信通知");
            } else {
                obj = methodProxy.invoke(buyer, objects);
            }

            return obj;
        });


        Ticketer proxy = (Ticketer) enhancer.create();
        proxy.login("zhangsan", "123456");
        proxy.buyTicket();

    }


}


class Ticketer {

    private String username;

    public Ticketer(String username) {
        this.username = username;
    }

    public Ticketer() {
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void login(String username, String password) {
        System.out.println(username + "登录成功");
    }

    public void buyTicket() {
        System.out.println(username + "购票成功");
    }


}
